package moltencore.network.serverlobby.strategy;

import moltencore.config.Config;
import moltencore.game.loader.exception.GameCreationException;
import moltencore.network.protocol.CreateGame;
import moltencore.network.protocol.CreateGameResponse;
import moltencore.network.serverlobby.GameList;
import moltencore.network.serverlobby.exception.GameConnectionOpeningException;
import moltencore.game.Settings;
import spark.network.protocol.Base;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import org.apache.log4j.Logger;
import spark.utility.OutWrapper;

import java.util.Collection;

public class CreateGameStrategy implements IProtocolHandleStrategy<CreateGame> {
	private Logger logger = Logger.getLogger(CreateGameStrategy.class);

	private GameList gameList;

	public CreateGameStrategy(GameList gameList) {
		this.gameList = gameList;
	}

	@Override
	public void handle(CreateGame packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		System.out.println("packet.getTeams() = " + packet.getTeams());
		CreateGameResponse response = new CreateGameResponse(packet);
		try {
			Settings settings = new Settings(
					packet.getGameMode(), new String(packet.getGameName()), packet.getPlayerLimit(), packet.getTeams() ? 2 : 1,
					packet.getCriticalMass(),
					packet.getGravity(), packet.getWind(),
			        packet.getOrdinaryBubbleCount(), packet.getChainReactions(),
			        Config.getInstance().getPushCount(),
			        Config.getInstance().getOrdinaryBubbleProbability(),
			        packet.getRainbowBubbles() ? Config.getInstance().getRainbowBubbleProbability() : 0.0f,
			        packet.getGhostBubbles() ? Config.getInstance().getGhostBubbleProbability() : 0.0f,
			        packet.getBlazingBubbles() ? Config.getInstance().getBlazingBubbleProbability() : 0.0f);
			int gamePort = gameList.openGame(
					packet.getSession(),
					settings);
			response.setPort(gamePort);
		}
		catch(Settings.InvalidOrdinaryBubbleCountException e) {
			response.setGameNotCreated();
			response.setMessage("Invalid ordinary bubble count specified./n" + e.getMessage());
		}
		catch(Settings.InvalidCriticalMassException e) {
			response.setGameNotCreated( );
			response.setMessage("Invalid critical mass specified./n" + e.getMessage());
		}
		catch(Settings.InvalidPlayerLimitException e) {
			response.setGameNotCreated();
			response.setMessage("Invalid player limit specified./n" + e.getMessage());
		}
		catch(GameCreationException e) {
			logger.error(e);
			response.setGameNotCreated();
			response.setMessage(e.getMessage());
		}

		acknowledgement.value = response;
	}
}
